package com.bearhy.jqadmin.controller;

import com.alibaba.fastjson.JSONObject;
import com.bearhy.jqadmin.common.BaseResult;
import com.bearhy.jqadmin.model.JqadminUser;
import com.github.pagehelper.util.StringUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        Subject subject = SecurityUtils.getSubject();
        String principal = (String) subject.getPrincipal();
        if(StringUtil.isEmpty(principal)){
            return "login";
        }else{
            return "index";
        }
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public BaseResult login(HttpServletRequest request, JqadminUser user){
        BaseResult baseResult = new BaseResult();
        System.out.println(1);
        String error = null;
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getUserPassword());
        try {
            //token.setRememberMe(token.isRememberMe());//记住我
            subject.login(token);
        } catch (UnknownAccountException e) {
            error = "用户名不存在";
            baseResult.setMsg("用户名不存在");
            baseResult.setStatus(999);
        } catch (IncorrectCredentialsException e) {
            error = "密码错误";
            baseResult.setMsg("密码错误");
            baseResult.setStatus(999);
        } catch (AuthenticationException e) {
            //其他错误，比如锁定，如果想单独处理请单独catch处理
            error = "其他错误：" + e.getMessage();
        }
        if(error == null) {//出错了，返回登录页面
            baseResult.setUrl("/index");
        }
        System.out.println(JSONObject.toJSONString(baseResult));
        return baseResult;
    }

    @RequestMapping("welcome")
    public String welcome(){
        return "welcome";
    }
}
